package com.rzx.mybackend.service.Impl;

import com.rzx.mybackend.entity.Role;
import com.rzx.mybackend.entity.User;
import com.rzx.mybackend.mapper.RoleMapper;
import com.rzx.mybackend.mapper.UserMapper;
import lombok.AllArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * UserDetailsServiceImpl
 *
 * @author renzhexian
 * @date 2025/7/15
 */
@Service
@AllArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UserMapper userMapper;

    private final RoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //根据用户名查询用户信息
        User user = userMapper.selectByUserName(username);
        if (user == null) {
            throw new UsernameNotFoundException("该用户不存在");
        }
        String[] roleArray = roleMapper.selectByUserId(user.getUserId()).stream()
                .map(Role::getRoleName)
                .toArray(String[]::new);

        // 显式添加 {noop} 前缀表示明文密码
        String encodedPassword = "{noop}" + user.getPassword();

        // 返回 Spring Security 的 UserDetails 对象
        return org.springframework.security.core.userdetails.User.builder()
                .username(user.getUserName())
                .password(encodedPassword) // 此处使用了明文密码
                .roles(roleArray) // 当前用户角色
                .build();
    }
}
